package io.renren.modules.frt.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import io.renren.common.utils.MapUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.modules.frt.entity.DistrictEntity;
import io.renren.modules.frt.entity.MonitorExcelEntity;
import io.renren.modules.frt.entity.SumaryEntity;
import io.renren.modules.frt.entity.TaskEntity;
import io.renren.modules.frt.entity.TaskUserEntity;
import io.renren.modules.frt.entity.TemplateEntity;
import io.renren.modules.frt.service.BaseReport2Service;
import io.renren.modules.frt.service.CopReport3Service;
import io.renren.modules.frt.service.DistrictService;
import io.renren.modules.frt.service.FamilyReport5Service;
import io.renren.modules.frt.service.MonitorExcelService;
import io.renren.modules.frt.service.MonitorReport1Service;
import io.renren.modules.frt.service.ProReport4Service;
import io.renren.modules.frt.service.SumaryService;
import io.renren.modules.frt.service.TaskService;
import io.renren.modules.frt.service.TaskUserService;
import io.renren.modules.frt.service.TemplateService;
import io.renren.modules.frt.utils.tpl.ExcelUtils;
import io.renren.modules.frt.utils.tpl.SheetData;
import io.renren.modules.sys.constant.DictConst;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;

/**
 * 下级填报进度
 *
 * @author qibing.huang
 * @email abingtech@163.com
 * @date 2018-11-18 23:36:41
 */
@RestController
@RequestMapping("frt/taskuser")
public class TaskUserController extends AbstractController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private TaskUserService taskUserService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private FamilyReport5Service familyReport5Service;
	@Autowired
	private DistrictService districtService;
	@Autowired
	private BaseReport2Service baseReport2Service;
	@Autowired
	private ProReport4Service proReport4Service;
	@Autowired
	private CopReport3Service copReport3Service;
	@Autowired
	private MonitorReport1Service monitorReport1Service;
	@Autowired
	private MonitorExcelService monitorExcelService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private SumaryService sumaryService;

	/**
	 * 列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/list")
	@RequiresPermissions("frt:taskuser:list")
	public R list(@RequestParam Map<String, Object> params) {

		SysUserEntity shiroUser = this.getUser();

		TaskUserEntity query = new TaskUserEntity();
		query.setUserId(shiroUser.getUserId());
		if (DictConst.USER_LEVEL.COUNTRY.getKey() == shiroUser.getLevel() && "point".equals(MapUtils.toStr(params, "flag"))) {// 如果是指派
			query.setPointStatus(io.renren.modules.frt.constant.DictConst.POINT_STATUS.UNPOINT.getKey());
		}
		// 如果是管理员，查看已下发的就行
		if (DictConst.USER_LEVEL.ADMIN.getKey() == shiroUser.getLevel()) {
			query.setSendStatus(io.renren.modules.frt.constant.DictConst.SEND_STATUS.SENDED.getKey());
		} else if (DictConst.USER_LEVEL.NONE.getKey() == shiroUser.getLevel()) {

		} else {// 其他查看未上报的
			//query.setReportStatus(io.renren.modules.frt.constant.DictConst.REPORT_STATUS.UNREPORT.getKey());
		}

		PageUtils page = taskUserService.queryPage(params, query);
		
		List<TaskUserEntity> pageList = (List<TaskUserEntity>)page.getList();
		if(pageList != null && pageList.size() > 0) {
			for(TaskUserEntity tuser : pageList) {
				//判断上级用户是否汇总
				int count = sumaryService.selectCount(new EntityWrapper<SumaryEntity>().eq("user_id", tuser.getParentId())
						.eq("task_id", tuser.getTaskId()));
				if(count > 0) {
					tuser.setSumaryStatus(1);
				}else {
					tuser.setSumaryStatus(0);
				}
			}
		}
		return R.ok().put("page", page);

	}

	/**
	 * 下级列表
	 */
	@RequestMapping("/next")
	@RequiresPermissions("frt:taskuser:next")
	public R next(@RequestParam Map<String, Object> params) {

		SysUserEntity shiroUser = this.getUser();

		TaskUserEntity query = new TaskUserEntity();
		if (StringUtils.isNotEmpty(MapUtils.toStr(params, "id"))) {
			query.setId(Long.parseLong(MapUtils.toStr(params, "id")));
		}
		query.setLevel(shiroUser.getLevel() + 1);
		query.setUserId(shiroUser.getUserId());
		if ("sumary".equals(MapUtils.toStr(params, "flag"))) {
			query.setReportStatus(io.renren.modules.frt.constant.DictConst.REPORT_STATUS.REPORTED.getKey());
			
			String key = MapUtils.toStr(params, "key");
			if(StringUtils.isNotEmpty(key)) {
				query.setTaskName("%"+key+"%");
			}
		}

		PageUtils page = taskUserService.queryNextPage(params, query);
		return R.ok().put("page", page);

	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("frt:taskuser:info")
	public R info(@PathVariable("id") Long id) {
		TaskUserEntity taskUser = taskUserService.selectById(id);

		return R.ok().put("taskuser", taskUser);
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("frt:taskuser:save")
	public R save(@RequestBody TaskUserEntity taskUser) {
		taskUserService.insert(taskUser);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("frt:taskuser:update")
	public R update(@RequestBody TaskUserEntity taskUser) {
		taskUserService.updateById(taskUser);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("frt:taskuser:delete")
	public R delete(@RequestBody Long[] ids) {
		taskUserService.deleteBatchIds(Arrays.asList(ids));

		return R.ok();
	}

	/**
	 * 上报
	 */
	@RequestMapping("/report")
	@RequiresPermissions("frt:taskuser:report")
	@Transactional
	public R report(@RequestBody Long[] ids) {
		try {
			SysUserEntity shiroUser = this.getUser();
			// 1、逻辑上只有当前用户为省级、市级、县级才能上报上报 --> 填报人上报单独一个页面
			if (DictConst.USER_LEVEL.PROVINCE.getKey() == shiroUser.getLevel() || DictConst.USER_LEVEL.CITY.getKey() == shiroUser.getLevel()
					|| DictConst.USER_LEVEL.COUNTRY.getKey() == shiroUser.getLevel()
					|| DictConst.USER_LEVEL.NONE.getKey() == shiroUser.getLevel()) {
				List<TaskUserEntity> taskUserList = taskUserService.selectBatchIds(Arrays.asList(ids));
				if (taskUserList != null && taskUserList.size() > 0) {
					List<Long> taskIdList = new ArrayList<>();
					for (TaskUserEntity taskUser : taskUserList) {
						taskIdList.add(taskUser.getTaskId());

						if (taskUser.getPointStatus() == io.renren.modules.frt.constant.DictConst.POINT_STATUS.UNPOINT.getKey()) {
							return R.error("无法上报，任务[" + taskUser.getTaskId() + "]还未指派！");
						}
						if (DictConst.USER_LEVEL.NONE.getKey() == shiroUser.getLevel()
								&& (taskUser.getReportId() == null || taskUser.getReportId() == 0)) {
							return R.error("无法上报，任务[" + taskUser.getTaskId() + "]还未填报！");
						}
						taskUser.setReportStatus(io.renren.modules.frt.constant.DictConst.REPORT_STATUS.REPORTED.getKey());
						taskUser.setReportTime(new Date());
					}

					// 2、上报节点判断，超过不能上报
					List<TaskEntity> taskList = taskService.selectBatchIds(taskIdList);
					for (TaskEntity task : taskList) {
						if (DateUtils.truncatedCompareTo(new Date(), task.getNodeDate(), Calendar.DATE) > 0) {
							return R.error("无法上报，任务[" + task.getName() + "]已经过了上报时间！");
						}

						if (DictConst.USER_LEVEL.NONE.getKey() != shiroUser.getLevel()) {
							// 3、判断下级是否已经有人上报
							Long count = taskUserService.selectUnReportTaskByLevel(shiroUser.getLevel().longValue() + 1, task.getId(),
									shiroUser.getUserId());
							if (count == 0) {
								return R.error("无法上报，您还有没有填写上报数据的任务！");
							}

							// 4、判断是否已经统计汇总
							int count2 = sumaryService.selectCount(
									new EntityWrapper<SumaryEntity>().eq("user_id", this.getUserId()).eq("task_id", task.getId()));
							if (count2 == 0) {
								return R.error("无法上报，您还有没有统计汇总！");
							}
						}
						
						//上级已汇总了，下级不能再上报
						int count = sumaryService.selectCount(new EntityWrapper<SumaryEntity>().eq("user_id", shiroUser.getParentId())
								.eq("task_id", task.getId()));
						if(count > 0) {
							return R.error("上级已经统计汇总，不能再上报！");
						}
					}

					// 2、更新任务（事项）的上报转态、上报时间
					taskUserService.updateBatchById(taskUserList);
					return R.ok("上报成功");
				}
			} else {
				return R.error("权限不足,请联系管理员");
			}
		} catch (Exception e) {
			logger.error("上报失败", e);
		}
		return R.error("上报失败");
	}

	/**
	 * 判断是否进行了统计汇总
	 */
	@RequestMapping("/isSumaryedByDownload")
	public R isSumaryedByDownload(Long taskUserId) {
		SysUserEntity shiroUser = this.getUser();

		TaskUserEntity taskUser = taskUserService.selectById(taskUserId);

		if (DictConst.USER_LEVEL.NONE.getKey() != shiroUser.getLevel()) {
			int count2 = sumaryService
					.selectCount(new EntityWrapper<SumaryEntity>().eq("user_id", this.getUserId()).eq("task_id", taskUser.getTaskId()));
			if (count2 == 0) {
				return R.error("无数据，请统计汇总数据后下载！");
			}
		}
		return R.ok();
	}

	/**
	 * 下载时判断下级是否有上报数据
	 */
	@RequestMapping("/isReportedByDownload")
	public R isReportedByDownload(Long taskUserId) {
		SysUserEntity shiroUser = this.getUser();

		TaskUserEntity taskUser = taskUserService.selectById(taskUserId);

		if (DictConst.USER_LEVEL.NONE.getKey() != shiroUser.getLevel()) {
			Long count = taskUserService.selectUnReportTaskByLevel(shiroUser.getLevel().longValue() + 1, taskUser.getTaskId(),
					shiroUser.getUserId());
			if (count == 0) {
				return R.error("无数据，请通知下级上报数据后下载！");
			}
		}
		return R.ok();
	}

	/**
	 * 指派
	 */
	@RequestMapping("/point")
	@RequiresPermissions("frt:taskuser:point")
	@Transactional
	public R point(@RequestBody Map<String, Object> params) {
		try {
			String idsStr = MapUtils.toStr(params, "idsStr");
			String userIdStr = MapUtils.toStr(params, "userId");
			String[] userIdArr = MapUtils.toStr(params, "userId").split(",");
			if (userIdArr == null || userIdArr.length == 0) {
				return R.error("填报人user_id[" + userIdStr + "]错误");
			}

			Long[] ids = null;
			if (StringUtils.isNotEmpty(idsStr)) {
				String[] allIds = idsStr.split(",");
				ids = new Long[allIds.length];
				for (int i = 0; i < allIds.length; i++) {
					ids[i] = Long.parseLong(allIds[i]);
				}

				if (ids == null || ids.length == 0) {
					return R.error("任务（事项）id[" + idsStr + "]错误");
				}
			}

			SysUserEntity shiroUser = this.getUser();
			// 只有县级用户才能指派
			if (DictConst.USER_LEVEL.COUNTRY.getKey() == shiroUser.getLevel()) {
				List<TaskUserEntity> taskUserList = taskUserService.selectBatchIds(Arrays.asList(ids));
				if (taskUserList != null && taskUserList.size() > 0) {
					List<TaskUserEntity> pointTaskUser = new ArrayList<>();
					for (TaskUserEntity taskUser : taskUserList) {
						for (String userId : userIdArr) {// 一个任务可以指派多个填报人
							// 生成指派任务
							TaskUserEntity point = new TaskUserEntity();
							point.setReportStatus(io.renren.modules.frt.constant.DictConst.REPORT_STATUS.UNREPORT.getKey());
							point.setTaskId(taskUser.getTaskId());
							point.setUserId(Long.parseLong(userId));
							point.setPointTime(new Date());

							pointTaskUser.add(point);
						}
						// 修改为已指派
						taskUser.setPointStatus(io.renren.modules.frt.constant.DictConst.POINT_STATUS.POINTED.getKey());
						taskUser.setPointTime(new Date());
					}

					// 超过节点时间也不做限制
					taskUserService.insertBatch(pointTaskUser);

					taskUserService.updateBatchById(taskUserList);
					return R.ok("指派成功");
				}
			} else {
				return R.error("权限不足,请联系管理员");
			}
		} catch (Exception e) {
			logger.error("指派失败", e);
		}
		return R.error("指派失败");
	}

	/**
	 * 在线填报
	 */
	@RequestMapping("/online")
	@RequiresPermissions("frt:taskuser:online")
	@Transactional
	public R online(String id) {
		try {
			TaskUserEntity taskUser = taskUserService.selectById(id);

			Long reportId = 1l;// TODO:需要修改实际填报
			taskUser.setReportId(reportId);

			taskUserService.updateById(taskUser);

			SysUserEntity noneUser = sysUserService.selectById(taskUser.getUserId());
			Long countryId = noneUser.getParentId();

			SysUserEntity countryUser = sysUserService.selectById(countryId);
			Long cityId = countryUser.getParentId();

			SysUserEntity cityUser = sysUserService.selectById(cityId);
			Long provinceId = cityUser.getParentId();

			List<TaskUserEntity> parentTU = taskUserService.selectList(new EntityWrapper<TaskUserEntity>()
					.eq("task_id", taskUser.getTaskId()).in("user_id", new Object[] { countryId, cityId, provinceId }));
			for (TaskUserEntity tu : parentTU) {
				tu.setReportId(reportId);
			}
			taskUserService.updateBatchById(parentTU);// 方便上级查看填报数据

			return R.ok("在线填报成功");

		} catch (Exception e) {
			logger.error("在线填报失败", e);
		}
		return R.error("在线填报失败");
	}

	/**
	 * 下载汇总数据
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	@RequiresPermissions("frt:taskuser:download")
	public void download(@RequestParam("tempType") String tempType, @RequestParam(value = "taskUserId", required = false) Long taskUserId,
			@RequestParam(value = "sumaryId", required = false) Long sumaryId, @RequestParam(value = "flag", required = false) String flag,
			HttpServletResponse response) {
		TaskUserEntity taskUser = null;
		Long taskId = null;
		String dataSourceIds = "";
		SysUserEntity shiroUser = this.getUser();
		Integer level = shiroUser.getLevel();
		if ("sumary".equals(flag)) {// 汇总图表
			if (StringUtils.isEmpty(tempType) || sumaryId == null) {
				logger.error("参数不合法！");
				return;
			}
			SumaryEntity sumary = sumaryService.selectById(sumaryId);
			taskId = sumary.getTaskId();
			dataSourceIds = sumary.getDataSourceIds();
			
			taskUser = new TaskUserEntity();
			taskUser.setTaskId(taskId);
		} else if ("my".equals(flag)) {// 我的任务
			if (StringUtils.isEmpty(tempType) || taskUserId == null) {
				logger.error("参数不合法！");
				return;
			}
			taskUser = taskUserService.selectById(taskUserId);
			taskId = taskUser.getTaskId();
			Assert.isNull(taskUser, "参数taskUserId[" + taskUserId + "]错误");

			List<SumaryEntity> sumaryList = sumaryService.selectList(
					new EntityWrapper<SumaryEntity>().eq("user_id", this.getUserId()).eq("task_id", taskId).orderBy("create_time", false));
			if (sumaryList == null || sumaryList.size() == 0) {
				logger.error("参数不合法！");
				return;
			}
			SumaryEntity lastSumary = sumaryList.get(0);
			
			
			dataSourceIds = lastSumary.getDataSourceIds();// 我的汇总源
		} else if ("manager".equals(flag)) {// 下级数据统计
			if (StringUtils.isEmpty(tempType) || taskUserId == null) {
				logger.error("参数不合法！");
				return;
			}
			taskUser = taskUserService.selectById(taskUserId);
			taskId = taskUser.getTaskId();
			Assert.isNull(taskUser, "参数taskUserId[" + taskUserId + "]错误");

			if(DictConst.USER_LEVEL.COUNTRY.getKey() != level) {
				SumaryEntity lastSumary = sumaryService.selectOne(new EntityWrapper<SumaryEntity>().eq("user_id", taskUser.getUserId())
						.eq("task_id", taskId).eq("sumary_flag", 1));
				if (lastSumary == null) {
					logger.error("系统错误，未统计汇总下级数据！");
					return;
				}
				dataSourceIds = lastSumary.getDataSourceIds();// 下级用户的汇总源
			}
		}
		List<Long> userIdList = new ArrayList<>();

		StringBuffer title = new StringBuffer("");
		if (StringUtils.isNotEmpty(shiroUser.getProvince())) {
			title.append(districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", shiroUser.getProvince())).getName());
		}
		if (StringUtils.isNotEmpty(shiroUser.getCity())) {
			title.append(districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", shiroUser.getCity())).getName());
		}
		if (StringUtils.isNotEmpty(shiroUser.getCountry())) {
			title.append(districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", shiroUser.getCountry())).getName());
		}

		if (DictConst.USER_LEVEL.ADMIN.getKey() == level) {
			parseUserIdListByAdmin(flag, taskUser, dataSourceIds, userIdList, title, this.getUser());
		} else if (DictConst.USER_LEVEL.PROVINCE.getKey() == level) {
			parseUserIdListByProvice(flag, taskUser, dataSourceIds, userIdList, title, this.getUser());
		} else if (DictConst.USER_LEVEL.CITY.getKey() == level) {
			parseUserIdListByCity(flag, taskUser, dataSourceIds, userIdList, title, this.getUser());
		} else if (DictConst.USER_LEVEL.COUNTRY.getKey() == level) {
			parseUserIdListByCountry(flag, taskUser, dataSourceIds, userIdList, this.getUserId());
		}
		
		if (userIdList.size() == 0) {
			logger.info("任务还未指派给填报人！");
			return;
		}

		List<? extends Object> list = null;
		String sheetName = "";
		if ("forestry_monitor".equals(tempType)) {
			List<String> codeList = new ArrayList<>();

			List<MonitorExcelEntity> excelList = monitorExcelService
					.selectList(new EntityWrapper<MonitorExcelEntity>().isNotNull("index_code"));
			if (excelList == null || excelList.size() == 0) {
				logger.error("未上传excel模板！");
				return;
			}
			for (MonitorExcelEntity excel : excelList) {
				codeList.add(excel.getIndexCode());
			}

			list = monitorReport1Service.sumaryList(taskId, userIdList.toArray(new Long[userIdList.size()]), codeList);
			sheetName = ExcelUtils.TPL_MONITOR_REPORT1;
		} else if ("emonstration_base_investigation".equals(tempType)) {
			list = baseReport2Service.sumaryList(taskId, userIdList.toArray(new Long[userIdList.size()]));
			sheetName = ExcelUtils.TPL_BASE_REPORT2;
		} else if ("forestry_cooperatives".equals(tempType)) {
			list = copReport3Service.sumaryList(taskId, userIdList.toArray(new Long[userIdList.size()]));
			sheetName = ExcelUtils.TPL_COP_REPORT3;
		} else if ("large_operate_conditions".equals(tempType)) {
			list = proReport4Service.sumaryList(taskId, userIdList.toArray(new Long[userIdList.size()]));
			sheetName = ExcelUtils.TPL_PRO_REPORT4;
		} else if ("family_forest".equals(tempType)) {
			list = familyReport5Service.sumaryList(taskId, userIdList.toArray(new Long[userIdList.size()]));
			sheetName = ExcelUtils.TPL_FAMILY_REPORT5;
		}
		SheetData sd = new SheetData(sheetName);
		sd.addDatas(list);
		sd.put("title", title);
		sd.put("date", io.renren.common.utils.DateUtils.format(new Date(), "yyyy年MM月dd日"));

		try {
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition",
					String.format("attachment; filename=\"%s\"", new String((sheetName + ExcelUtils.SUBFIX).getBytes("GBK"), "ISO8859-1")));

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		try {
			ExcelUtils.writeData(sheetName + ExcelUtils.SUBFIX, response.getOutputStream(), sd);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	private void parseUserIdListByAdmin(String flag, TaskUserEntity taskUser, String dataSourceIds, List<Long> userIdList,
			StringBuffer title, SysUserEntity adminUser) {
		List<SysUserEntity> provinceList = new ArrayList<>();
		if("manager".equals(flag)) {
			provinceList.add(sysUserService.selectById(taskUser.getUserId()));
		}else {
			provinceList = sysUserService.selectList(new EntityWrapper<SysUserEntity>().eq("parent_id", adminUser.getUserId())
					.in(StringUtils.isNotEmpty(dataSourceIds), "province", dataSourceIds)
					.eq("level", DictConst.USER_LEVEL.PROVINCE.getKey()).eq("check_status", 1));
		}
		
		if (provinceList != null && provinceList.size() > 0) {
			for (SysUserEntity user : provinceList) {
				SumaryEntity lastSumary = sumaryService.selectOne(new EntityWrapper<SumaryEntity>().eq("user_id", user.getUserId())
						.eq("task_id", taskUser.getTaskId()).eq("sumary_flag", 1));
				if (lastSumary == null) {
					logger.error("系统错误，下级未统计汇总！");
					return;
				}
				dataSourceIds = lastSumary.getDataSourceIds();

				this.parseUserIdListByProvice(flag, taskUser, dataSourceIds, userIdList, title, user);
			}
		}
	}

	private void parseUserIdListByProvice(String flag, TaskUserEntity taskUser, String dataSourceIds, List<Long> userIdList,
			StringBuffer title, SysUserEntity proviceUser) {
		List<SysUserEntity> cityList = new ArrayList<>();
		if("manager".equals(flag) && this.getUser().getLevel() != DictConst.USER_LEVEL.ADMIN.getKey()) {
			cityList.add(sysUserService.selectById(taskUser.getUserId()));
		}else {
			cityList = sysUserService.selectList(new EntityWrapper<SysUserEntity>().eq("parent_id", proviceUser.getUserId())
					.in(StringUtils.isNotEmpty(dataSourceIds), "city", dataSourceIds).eq("level", DictConst.USER_LEVEL.CITY.getKey())
					.eq("check_status", 1));
		}

		if (cityList != null && cityList.size() > 0) {
			for (SysUserEntity user : cityList) {
				SumaryEntity lastSumary = sumaryService.selectOne(new EntityWrapper<SumaryEntity>().eq("user_id", user.getUserId())
						.eq("task_id", taskUser.getTaskId()).eq("sumary_flag", 1));
				if (lastSumary == null) {
					logger.error("系统错误，下级未统计汇总！");
					return;
				}
				dataSourceIds = lastSumary.getDataSourceIds();

				parseUserIdListByCity(flag, taskUser, dataSourceIds, userIdList, title, user);
			}

		}
	}

	private void parseUserIdListByCity(String flag, TaskUserEntity taskUser, String dataSourceIds, List<Long> userIdList,
			StringBuffer title, SysUserEntity cityUser) {
		List<SysUserEntity> countryList = new ArrayList<>();
		if("manager".equals(flag) && this.getUser().getLevel() != DictConst.USER_LEVEL.ADMIN.getKey()) {
			countryList.add(sysUserService.selectById(taskUser.getUserId()));
		}else {
			countryList = sysUserService.selectList(new EntityWrapper<SysUserEntity>().eq("parent_id", cityUser.getUserId())
					.in(StringUtils.isNotEmpty(dataSourceIds), "country", dataSourceIds)// 县级的
					.eq("level", DictConst.USER_LEVEL.COUNTRY.getKey()).eq("check_status", 1));
		}

		if (countryList != null && countryList.size() > 0) {
			for (SysUserEntity user : countryList) {
				SumaryEntity lastSumary = sumaryService.selectOne(new EntityWrapper<SumaryEntity>().eq("user_id", user.getUserId())
						.eq("task_id", taskUser.getTaskId()).eq("sumary_flag", 1));
				if (lastSumary == null) {
					logger.error("系统错误，下级未统计汇总！");
					return;
				}
				dataSourceIds = lastSumary.getDataSourceIds();
				parseUserIdListByCountry(flag, taskUser, dataSourceIds, userIdList, user.getUserId());
			}
		}
	}

	private void parseUserIdListByCountry(String flag, TaskUserEntity taskUser, String dataSourceIds, List<Long> userIdList,
			Long countryId) {
		if("manager".equals(flag) && this.getUser().getLevel() != DictConst.USER_LEVEL.ADMIN.getKey()) {
			if (taskUser != null && taskUser.getUserId() != null) {// 已经确定了填报人
				userIdList.add(taskUser.getUserId());
			}
		}else {
			List<SysUserEntity> userList = sysUserService.selectList(new EntityWrapper<SysUserEntity>()
					.eq("level", DictConst.USER_LEVEL.NONE.getKey()).in(StringUtils.isNotEmpty(dataSourceIds), "username", dataSourceIds)
					.eq("check_status", 1).eq("parent_id", countryId));
			if (userList != null && userList.size() > 0) {
				for (SysUserEntity user : userList) {
					userIdList.add(user.getUserId());
				}
			}
		}
	}

	/**
	 * 统计汇总
	 */
	@RequestMapping("/sumary")
	public R sumary(@RequestBody Map<String, Object> params) {
		
		String sumaryName = MapUtils.toStr(params, "sumaryName");
		if (StringUtils.isEmpty(sumaryName)) {
			return R.error("汇总表名称不能为空！");
		}
		
		String taskUserIds = MapUtils.toStr(params, "ids");
		String[] taskUserIdsArr = MapUtils.toStr(params, "ids").split(",");
		if (taskUserIdsArr == null || taskUserIdsArr.length == 0) {
			return R.error("选择的任务task_user_id[" + taskUserIds + "]错误");
		}

		Long[] ids = null;
		ids = new Long[taskUserIdsArr.length];
		for (int i = 0; i < taskUserIdsArr.length; i++) {
			ids[i] = Long.parseLong(taskUserIdsArr[i]);
		}
		List<Long> taskUserIdList = Arrays.asList(ids);

		Set<String> dataSource = new HashSet<>();
		Set<String> dataSourceId = new HashSet<>();
		Integer level = this.getUser().getLevel();

		StringBuffer sui = new StringBuffer();
		String taskName = "", tempName = "";
		TaskEntity task = null;
		TemplateEntity temp = null;
		for (Long taskUserId : taskUserIdList) {
			TaskUserEntity taskUser = taskUserService.selectById(taskUserId);
			task = taskService.selectById(taskUser.getTaskId());
			temp = templateService.selectById(task.getTempId());
			if (taskName == "") {
				taskName = task.getName();
			} else {
				if (!taskName.equals(task.getName())) {
					return R.error("请相同任务的数据");
				}
			}
			if (tempName == "") {
				tempName = temp.getName();
			} else {
				if (!tempName.equals(temp.getName())) {
					return R.error("请相同模板类型的数据");
				}
			}

			SysUserEntity user = sysUserService.selectById(taskUser.getUserId());
			if (DictConst.USER_LEVEL.ADMIN.getKey() == level) {
				DistrictEntity de = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", user.getProvince()));
				dataSource.add(de.getName());
				dataSourceId.add(de.getCode());
			} else if (DictConst.USER_LEVEL.PROVINCE.getKey() == level) {
				DistrictEntity de = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", user.getCity()));
				dataSource.add(de.getName());
				dataSourceId.add(de.getCode());
			} else if (DictConst.USER_LEVEL.CITY.getKey() == level) {
				DistrictEntity de = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", user.getCountry()));
				dataSource.add(de.getName());
				dataSourceId.add(de.getCode());
			} else if (DictConst.USER_LEVEL.COUNTRY.getKey() == level) {
				dataSource.add(user.getUsername());
				dataSourceId.add(user.getUsername());
			}
			sui.append(taskUserId).append(",");
		}

		StringBuffer ds = new StringBuffer();
		Iterator<String> itor = dataSource.iterator();
		while (itor.hasNext()) {
			ds.append(itor.next()).append(",");
		}
		if (ds.length() > 0) {
			ds.setLength(ds.length() - 1);
		}

		StringBuffer dsId = new StringBuffer();
		Iterator<String> itor2 = dataSourceId.iterator();
		while (itor2.hasNext()) {
			dsId.append(itor2.next()).append(",");
		}
		if (dsId.length() > 0) {
			dsId.setLength(dsId.length() - 1);
		}
		
		List<SumaryEntity> oldSumList = sumaryService.selectList(new EntityWrapper<SumaryEntity>().eq("user_id", this.getUserId()).eq("task_id", task.getId()));
		if(oldSumList != null && oldSumList.size() > 0) {
			for(SumaryEntity se : oldSumList) {
				se.setSumaryFlag(0);
			}
			sumaryService.updateBatchById(oldSumList);
		}
		
		SumaryEntity sumary = new SumaryEntity();
		sumary.setCreateTime(new Date());
		sumary.setDataSource(ds.toString());
		sumary.setNodeDate(task.getNodeDate());
		sumary.setTaskName(task.getName());

		sui.setLength(sui.length() - 1);
		sumary.setTaskUserIds(sui.toString());
		sumary.setTempName(tempName);
		sumary.setUserId(this.getUserId());
		sumary.setTaskId(task.getId());
		sumary.setTempType(temp.getType());
		sumary.setDataSourceIds(dsId.toString());
		
		sumary.setSumaryName(sumaryName);
		sumary.setSumaryFlag(1);

		sumaryService.insert(sumary);

		return R.ok();
	}

}
